package com.sari.common.utils;

import org.apache.commons.lang.time.DateFormatUtils;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
 */
public class DateUtils extends org.apache.commons.lang.time.DateUtils {

    private static Logger logger = LoggerFactory.getLogger(DateUtils.class);

    private static String[] parsePatterns = {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm"};

    /**
     * 得到当前日期字符串 格式（yyyy-MM-dd）
     */
    public static String getDate() {
        return getDate("yyyy-MM-dd");
    }

    /**
     * 得到当前日期字符串 格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String getDate(String pattern) {
        return DateFormatUtils.format(new Date(), pattern);
    }

    /**
     * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String formatDate(Date date, Object... pattern) {
        String formatDate = null;
        if (pattern != null && pattern.length > 0) {
            formatDate = DateFormatUtils.format(date, pattern[0].toString());
        } else {
            formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatDate;
    }

    /**
     * 根据时间字符串和字符串格式,转换成java.util.Date对象
     *
     * @param dateString
     * @param format
     * @return
     */
    public static Date formatStringToDate(String dateString,String format){
        format = format!=null?format:"yyyy-MM-dd HH:mm:ss";
        if(dateString==null||dateString.length()==0) return null;
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        Date date = new Date();
        try {
            date = dateFormat.parse(dateString);

        } catch (ParseException e){
            logger.warn(Exceptions.getStackTraceAsString(e));
        }
        return date;
    }


    /**
     * 得到日期时间字符串，转换格式（yyyy-MM-dd HH:mm:ss）
     */
    public static String formatDateTime(Date date) {
        return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static String formatDate(Date date) {
        return formatDate(date, "yyyy-MM-dd");
    }

    /**
     * 得到当前时间字符串 格式（HH:mm:ss）
     */
    public static String getTime() {
        return formatDate(new Date(), "HH:mm:ss");
    }
    /**
     * 得到当前时间毫秒数，时间戳
     */
    public static String getTimeMillis(){
        return String.valueOf(System.currentTimeMillis());
    }

    /**
     * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm:ss）
     */
    public static String getDateTime() {
        return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 得到当前年份字符串 格式（yyyy）
     */
    public static String getYear() {
        return formatDate(new Date(), "yyyy");
    }

    /**
     * 得到当前月份字符串 格式（MM）
     */
    public static String getMonth() {
        return formatDate(new Date(), "MM");
    }

    public static String getYearMonth(int i) {
        String strDate = formatDate(new Date(), "yyyy-MM");
        String strYear = strDate.substring(0, 5);
        int month = Integer.parseInt(strDate.substring(5, 7));
        int mon = month + i;

        if(mon <= 0){
            mon = 12 + (mon);
        }
        if(mon > 12){
            mon = mon -12;
        }

        String strMon = String.valueOf(mon).length()==1 ? "0"+String.valueOf(mon) : String.valueOf(mon);

        return strYear + strMon;
    }

    /**
     * 得到当天字符串 格式（dd）
     */
    public static String getDay() {
        return formatDate(new Date(), "dd");
    }

    /**
     * 得到当前星期字符串 格式（E）星期几
     */
    public static String getWeek() {
        return formatDate(new Date(), "E");
    }

    /**
     * 日期型字符串转化为日期 格式
     * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
     * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            logger.warn(Exceptions.getStackTraceAsString(e));
            return null;
        }
    }

    /**
     * 获取过去的天数
     *
     * @param date
     * @return
     */
    public static long pastDays(Date date) {
        long t = new Date().getTime() - date.getTime();
        return t / (24 * 60 * 60 * 1000);
    }


    public static Date getDateStart(Date date) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date = sdf.parse(formatDate(date, "yyyy-MM-dd") + " 00:00:00");
        } catch (ParseException e) {
            logger.warn(Exceptions.getStackTraceAsString(e));
        }
        return date;
    }

    public static Date getDateEnd(Date date) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date = sdf.parse(formatDate(date, "yyyy-MM-dd") + " 23:59:59");
        } catch (ParseException e) {
            logger.warn(Exceptions.getStackTraceAsString(e));
        }
        return date;
    }

    public static Date formatLongToDate(Long beginDate){
        return new Date(beginDate);
    }

    //日期推多少，num：向前为负，向后为正
    public static Date rollNOfDate(Date date,int dateType,int num) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        switch(dateType){
            case 1:{//天
                cal.add(Calendar.DAY_OF_MONTH, num);
                break;
            }
            case 2:{//周
                cal.add(Calendar.DAY_OF_MONTH, 7*num);
                break;
            }
            case 3:{//月
                cal.add(Calendar.MONTH, num);
                break;
            }
            case 4:{//季度
                cal.add(Calendar.MONTH, 3*num);
                break;
            }
            case 5:{//年
                cal.add(Calendar.YEAR, num);
                break;
            }
            case 6:{//小时
                cal.add(Calendar.HOUR, num);
                break;
            }
        }
        return cal.getTime();
    }


    public static String getBirthday(String age){
        Calendar c = Calendar.getInstance();
        String m_d = "-01-01 00:00:00";
        int year = c.get(Calendar.YEAR);
        int y = year - Integer.valueOf(age);
        return String.valueOf(y) + m_d;
    }

    /**
     * 毫秒数转换为 * days * hours * minutes * seconds 后的格式
     * @param mss
     * @return
     */
    public static String formatDuring(long mss) {
        long days = mss / (1000 * 60 * 60 * 24);
        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (mss % (1000 * 60)) / 1000;
        return days + " days " + hours + " hours " + minutes + " minutes "
                + seconds + " seconds ";
    }

    public static boolean compareDate(String DATE1, String DATE2,String type) {


        DateFormat df = new SimpleDateFormat(type);
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
               //"dt1 >dt2前"
                return false;
            } else if (dt1.getTime() < dt2.getTime()) {
                return true;
            }else{
                return true;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }
    /**
     * @param args
     * @throws ParseException
     */
    public static void main(String[] args) throws ParseException {
        String name = "ww=12&ww=34";
        String[] name2 = name.split("&");
       System.out.print(name2[0]);
        System.out.print(name2[1]);

    }

    public static String getLastDate(String dateTime){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar lastDate = Calendar.getInstance();
        try {
            lastDate.setTime(sdf.parse(dateTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 设置为这个月的第 1 天
        lastDate.set(Calendar.DATE, 1);
        lastDate.add(Calendar.MONTH, 1);
        lastDate.add(Calendar.DATE, -1);
        String format = sdf.format(lastDate.getTime());

        return format;
    }

    public static List getDatesByWeek(String week,int month){

        String [] weeks = week.split(",");
        List list = new ArrayList();
        List<String> dList = getDayListByMonth(month);
        for(String d:dList){
            if(getDayForWeek(d).equals(weeks[0])&&
                    DateUtils.compareDate(weeks[1],d,"yyyy-MM-dd")&&DateUtils.compareDate(d,weeks[2],"yyyy-MM-dd")){
                list.add(d);
            }
        }
        return list;
       /** SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Integer.valueOf(getYear()), month, 1);
        int i = 1;
        while (calendar.get(calendar.MONTH) < month + 1) {
            calendar.set(calendar.WEEK_OF_YEAR, i++);
            calendar.set(calendar.DAY_OF_WEEK, week);
            if (calendar.get(calendar.MONTH) == month) {
                list.add(sdf.format(calendar.getTime()));
            }
        }
        return list;**/
    }

    public static String getDayForWeek(String pTime) {

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(format.parse(pTime));
            int dayForWeek = 0;
            if(c.get(Calendar.DAY_OF_WEEK) == 1){
                //星期天
                dayForWeek = 0;
            }else{
                dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
            }
            return String.valueOf(dayForWeek);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static int getMonthByDate(String dateStr){

        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr );
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        int month = ca.get(Calendar.MONTH);
        return month+1;
    }

    //获取一个月所有日期
    public static List getDayListByMonth(int month) {

        List<String> list = new ArrayList();
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        String year = DateUtils.getYear();
        aCalendar.set(Integer.valueOf(year), month-1, 1);
        int day = aCalendar.getActualMaximum(aCalendar.DATE);
        for (int i = 1; i <= day; i++) {
            String d = year+"-"+(month<10?"0"+month:month)+"-"+(i<10?"0"+i:i);
            list.add(d);
        }
        return list;
    }

    public static String getWeek(String week){
        String s = "";
        switch (week){
            case "1":s="一";
                break;
            case "2":s="二";
                break;
            case "3":s="三";
                break;
            case "4":s="四";
                break;
            case "5":s="五";
                break;
            case "6":s="六";
                break;
            case "0":s="日";
                break;
        }
        return s;
    }
}
